/*
 *    Copyright (c) 2018-2025, lengleng All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the pig4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: lengleng (wangiegie@gmail.com)
 */
package com.pig4cloud.pig.ads.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.api.client.util.Lists;
import com.pig4cloud.pig.ads.config.SdkProperties;
import com.pig4cloud.pig.ads.pig.mapper.AdIndustryMapper;
import com.pig4cloud.pig.ads.service.AdIndustryService;
import com.pig4cloud.pig.ads.service.TtAccesstokenService;
import com.pig4cloud.pig.ads.utils.OEHttpUtils;
import com.pig4cloud.pig.api.entity.AdIndustry;
import com.pig4cloud.pig.api.entity.ResponseBean;
import com.pig4cloud.pig.api.entity.TtAccesstoken;
import com.pig4cloud.pig.api.vo.AdIndustryRes;
import com.xxl.job.core.log.XxlJobLogger;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 巨量行业列表
 *
 * @author yuwenfeng
 * @date 2022-02-08 15:28:03
 */
@Log4j2
@Service
@RequiredArgsConstructor
public class AdIndustryServiceImpl extends ServiceImpl<AdIndustryMapper, AdIndustry> implements AdIndustryService {

	private final TtAccesstokenService ttAccesstokenService;

	private final SdkProperties sdkProperties;

	@Override
	public List<AdIndustryRes> selectAdIndustryResAll(QueryWrapper<AdIndustry> queryWrapper) {
		List<AdIndustryRes> list = baseMapper.selectIndustryResList(new QueryWrapper<AdIndustry>());
		if (CollectionUtils.isNotEmpty(list)) {
			return list.stream().filter(m -> m.getLevel() == 1).map(
					(m) -> {
						m.setChildren(getChildrens(m, list));
						return m;
					}
			).collect(Collectors.toList());
		}
		return list;
	}

	/**
	 * @description: 递归子集合数据
	 * @author yuwenfeng
	 * @date 2022/2/8 16:38
	 */
	private List<AdIndustryRes> getChildrens(AdIndustryRes res, List<AdIndustryRes> all) {
		return all.stream().filter(m -> {
			if (1 == res.getLevel()) {
				return Objects.equals(m.getFirstIndustryId(), res.getFirstIndustryId()) && m.getLevel() == 2;
			} else if (2 == res.getLevel()) {
				return Objects.equals(m.getSecondIndustryId(), res.getSecondIndustryId()) && m.getLevel() == 3;
			}
			return false;
		}).map(
				(m) -> {
					m.setChildren(getChildrens(m, all));
					return m;
				}
		).collect(Collectors.toList());
	}

	@Override
	public void getIndustryList(String param) {
		XxlJobLogger.log("-----------------获取行业列表开始---------------------");
		long start = System.currentTimeMillis();
		List<AdIndustry> industryList = Lists.newArrayList();
		TtAccesstoken ttAccesstoken = ttAccesstokenService.getOne(new QueryWrapper<TtAccesstoken>().eq("housekeeper", 2).orderByDesc("updatetime").last("LIMIT 1"));
		if (null != ttAccesstoken && StringUtils.isNotBlank(ttAccesstoken.getAccessToken())) {
			try {
				Map<String, Object> data = new HashMap<String, Object>(1);
				data.put("type", "ADVERTISER");
				//调第三方平台（头条）接口
				String resultStr = OEHttpUtils.doGet(sdkProperties.getAdIndustryListUrl(), data, ttAccesstoken.getAccessToken());
//				XxlJobLogger.log("-----------------获取行业接口返回值：{}---------------------",resultStr);
				ResponseBean resBean = JSON.parseObject(resultStr, ResponseBean.class);
				if (resBean != null && "0".equals(resBean.getCode())) {
					JSONObject jsonObj = resBean.getData();
					JSONArray arr = JSON.parseArray(String.valueOf(jsonObj.get("list")));
					if (arr.size() > 0) {
						XxlJobLogger.log("-----------------获取行业接口数据条数：{}---------------------",arr.size());
						baseMapper.deleteAllIndustry();
						AdIndustry info;
						for (Object obj : arr) {
							JSONObject jsonObject = (JSONObject) obj;
							info = new AdIndustry();
							info.setIndustryId(jsonObject.getLong("industry_id"));
							info.setIndustryName(jsonObject.getString("industry_name"));
							info.setLevel(jsonObject.getInteger("level"));
							info.setFirstIndustryId(jsonObject.getLong("first_industry_id"));
							info.setFirstIndustryName(jsonObject.getString("first_industry_name"));
							info.setSecondIndustryId(jsonObject.getLong("second_industry_id"));
							info.setSecondIndustryName(jsonObject.getString("second_industry_name"));
							info.setThirdIndustryId(jsonObject.getLong("third_industry_id"));
							info.setThirdIndustryName(jsonObject.getString("third_industry_name"));
							info.setCreateTime(new Date());
							info.setUpdateTime(new Date());
							industryList.add(info);
						}
					}
				} else {
					log.info(">>>获取行业列表，拉取失败，原因：{}", resBean.getMessage());
					XxlJobLogger.log(">>>获取行业列表，拉取失败，原因：{}", resBean.getMessage());
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		if (industryList.size() > 0) {
			// 批量插入数据
			this.saveBatch(industryList);
		}
		long end = System.currentTimeMillis();
		XxlJobLogger.log("-----------------获取行业列表结束，耗时：" + (end - start) / 1000 + "秒---------------------");
	}

	/*public static void main(String[] args) {
		String url = "https://ad.oceanengine.com/open_api/2/tools/industry/get/";
		String accessToken = "65c36e35cc36ad69de8cef431ae973e904664a4b";
		Map<String, Object> data = new HashMap<String, Object>(1);
		data.put("type", "ADVERTISER");
		//调第三方平台（头条）接口
		String resultStr = OEHttpUtils.doGet(url, data, accessToken);
		System.out.println(">>>>>>1" + resultStr);
		ResponseBean resBean = JSON.parseObject(resultStr, ResponseBean.class);
		System.out.println(">>>>>>2" + JSON.toJSONString(resBean));
	}*/
}
